<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class epaper_upload_model extends model {

	private $base_url='https://www.chinaluan.com/html/';
	private $epaperDb;
	public $catid = 7;

	function __construct() {
		$this->db_config = pc_base::load_config('database');
		$this->db_setting = 'default';
		$this->table_name = 'epaper_upload';
		$this->epaperDb = pc_base::load_model('content_model');
		parent::__construct();
	}

	// web 抓取数字报
	// web 格式
	// $publish_date href 中的时间
	// $publish_date2 真实的日期 用于处理 202304281 问题
	// 
	function grabAdd(string $publish_date, string $publish_date2=""){
		if(!$publish_date2)
			$publish_date2 = $publish_date;

		$date2 = $publish_date;
		$file_base_url = $this->base_url.$date2.'/';
		$extract_path = 'uploadfile/epaper/'.$date2.'/';

		// 清空目录
		deleteDir($extract_path);

		// 跳过ssl验证
		$stream_opts = [
			"ssl" => [
				"verify_peer"=>false,
				"verify_peer_name"=>false,
			]
		];
		
		
		// 读取sfv文件内容
		$sfv_name = $date2.'.sfv';
		$sfv_content =  file_get_contents($file_base_url.$sfv_name, false, stream_context_create($stream_opts));
		
		if(!$sfv_content)
			throw new Exception('配置文件抓取失败');
		
		// 创建目录
		if(file_exists($extract_path))
			throw new Exception($extract_path.'已存在，请先删除该目录后再上传');
		
		mkdir($extract_path);
		
		// 保存sfv文件
		$rt = file_put_contents($extract_path.$sfv_name, $sfv_content);
		if($rt === false){
			throw new Exception('文件保存失败'.$extract_path.$sfv_name);
		}
		
		$r = explode("\n", $sfv_content);
		
		foreach($r as $index=>$line){
			if($index == 0)
				continue;
			if(!$line)
				continue;
			
			$file_name = current(explode(' ', $line));

			// swf exe 文件不需要下载
			$ext = end(explode('.',$file_name));
			if($ext == 'swf' || $ext == 'exe')
				continue;


			$rt = file_put_contents($extract_path.$file_name, file_get_contents($file_base_url.$file_name,false,stream_context_create($stream_opts)));
			if(!$rt){
				throw new Exception('文件抓取失败：'.$file_base_url.$file_name);
			}
		}
		
		// 解压信息入库
		$ins = [
			'date'=> $publish_date2,
			'resource_dir'=> $extract_path,
			'sfv_rar_dir'=> '',
			'sfv_name'=> $sfv_name,
		];
		
		return $this->insert($ins,true);
	}

	/**
	 * epaper 文件解析
	 * web 格式
	 */
	public function analysisCfg(int $id=0) {
		// phpinfo();die;

		$one = $this->get_one(['id'=>$id]);
		if(!$one)
			throw new Exception('发生错误！不存在 epaper_upload:'.$id);

		// 检测是否添加过该文章
		$this->epaperDb->set_catid($this->catid);

		// 检测这一期是否已经生成
		$r = $this->epaperDb->get_one(['date'=>$one['date']]);
		if($r)
			throw new Exception('数字报新闻'.$one['date'].'期已存在，请先删除相关新闻后再解析');

		// 配置文件存在
		if(!$one['sfv_name']){			
			return $this->analysisCfg2($id);
		}

		// 解压后的文件目录
		$relate_dir = $one['resource_dir'].$one['sfv_rar_dir'];
		$sfv_path = $relate_dir.$one['sfv_name'];
		
		// 读取 sfv 配置文件内容
		$file = fopen($sfv_path, "r");
		if(!$file)
			throw new Exception('打开文件失败：'.$sfv_path);
		// sfv文件中的清单
		$file_names = [];
		while(!feof($file)){
			$line = fgets($file);
			if($line === false)
				break;
			$arr = explode(' ', $line);
			$file_names[] = $arr[0];
			// echo fgets($file). "<br />";
		}
		fclose($file);
		// 查找 cfg 文件
		$cfg_name = '';
		foreach($file_names as $name){
			$ext = end(explode('.', $name));
			if($ext == 'cfg'){
				$cfg_name = $name;
				break;
			}
		}

		// 读取 cfg 文件内容
		$cfg_path = $relate_dir.$cfg_name;

		$xml = simplexml_load_file($cfg_path);

		// $a1 = $xml->PageList->attributes();
		foreach($xml->PageList->Page as $page){

			$page_number = (string)$page->attributes()->Number;
			$page_name = (string)$page->attributes()->Name;
			$page_xml_name = (string)$page->attributes()->XML;
			$page_image_name = (string)$page->attributes()->Image;

			
			$page_image_path = $relate_dir.$page_image_name;
			// 读取 xml 数据
			
			$page_xml_path = $relate_dir.$page_xml_name;
			$page_xml = simplexml_load_file($page_xml_path);

			// 解析 page_xml 文章数据
			$this->analysisArticle($page_xml, $relate_dir, $page_image_path, $one['date'], $page_number, $page_name);
		}
	}

	/**
	 * epaper 文件解析
	 * rar 格式
	 */
	public function analysisCfg2(int $id=0) {
		// die("卷起来");

		$one = $this->get_one(['id'=>$id]);
		if(!$one)
			throw new Exception('发生错误！不存在 epaper_upload:'.$id);

		// 解压后的文件目录
		$relate_dir = $one['resource_dir'].$one['sfv_rar_dir'];
		$sfv_path = $relate_dir.$one['sfv_name'];

		$one['sfv_rar_dir'];
		// 读取文件列表信息

		$list = scandir($relate_dir);

		if(!$list)
			throw new Exception("读取目录信息失败，请勿使用中文及特殊符号：".$relate_dir);


		$dir_list = []; // 排序分版
		$image_list = []; // 排序 按位对
		foreach($list as $val){

			$ext = end(explode('.',$val));
			$ext = strtolower($ext);

			// 文件夹
			if($ext == 'files'){
				$dir_list[] = $val;
				continue;
			}

			// 版面图
			if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png'){
				$image_list[] = $val;
				continue;
			}
		}

		if(!sort($dir_list))
			throw new Exception('dir sort排序失败');
		if(!sort($image_list))
			throw new Exception('image sort排序失败');

		if(count($image_list) < count($dir_list))
			throw new Exception('缺少封面图，封面图数量：'.count($image_list));

		foreach($dir_list as $index=>$dir){

			$page_image_path = $image_list[$index];

			// xml 配置文件
			$xml_path = '';
			$list = scandir($relate_dir.'/'.$dir);
			foreach($list as $val2){
				// 查找配置文件
				if(strpos($val2, '.xml') !== false){
					$xml_path = $val2;
					break;
				}
			}

			// 读取 xml 数据
			$page_xml = simplexml_load_file($relate_dir.'/'.$dir.'/'.$xml_path);
			if(!$page_xml)
				throw new Exception('文件解析失败xml:'.$relate_dir.'/'.$dir.'/'.$xml_path);

			// 解析 page_xml 文章数据
			$this->analysisArticle($page_xml, $relate_dir.'/'.$dir.'/images/', $relate_dir.'/'.$page_image_path, $one['date']);
		}
	}

	/**
	 * epaper page 中的文章解析
	 * $relate_dir 文件的dir相对路径
	 */
	private function analysisArticle(SimpleXMLElement $page, string $relate_dir, string $page_image_path, string $date) {

		$page_number = $page->PageInfo->attributes()->PageNo;
		$page_name = $page->PageInfo->attributes()->PageName;

		foreach($page->ArticleList->Article as $article){

			// (string)$article->IntroTitle;
			// (string)$article->Title;
			// (string)$article->SubTitle;
			// (string)$article->Author;
			// (string)$article->Source;
			// (string)$article->Content;
	
			(string)$article->ImageList;

			// 获取热区
			$points = '';
			foreach($article->PointList->Point as $point){
				$x = (string)$point->attributes()->X;
				$y = (string)$point->attributes()->Y;
				$points .= $x.','.$y.',';
			}
			if($points != '')
				$points = substr($points, 0, strlen($points)-1);
	
			// 解析图片数据
			// $_POST = [];
			// $_POST['image_url'] = [];
			// $_POST['image_alt'] = [];
			$imgStr = '';
			$firImgStr = '';
			foreach($article->ImageList->Image as $image){
				$image_name = (string)$image->attributes()->Name;
				// $_POST['image_url'][] = $relate_dir.$image_name;
				// $_POST['image_alt'][] = $image_name;
				$imgStr .= $this->contentImage($relate_dir.$image_name, $image_name);
				if(!$firImgStr)
					$firImgStr = $relate_dir.$image_name;
			}
			
	
			// 检索标题 = 日期+版面+标题
			$title = date('Ymd', strtotime($date)).'|'.$page_number.'|'.trim((string)$article->Title);

			$description = mb_ereg_replace("　","",(string)$article->Content);
			$description = str_replace([" ","\t","\n","\r"], '', $description);
			$description = html_entity_decode($description);
			
			$ins = [
				'catid'=>$this->catid,
				'status'=>99,
				'thumb'=>$firImgStr, // 封面图
				'title'=>$title,
				'title2'=>trim((string)$article->Title),
				'username'=>'文件上传',
				'date'=>$date,
				'intro_title'=>trim((string)$article->IntroTitle),
				'sub_title'=>trim((string)$article->SubTitle),
				'image'=>'解析占位用勿删',// 这里修改无效 会重新从 $_POST 取值
				'author'=>trim((string)$article->Author),
				'points'=>$points,
				'page'=>$page_number,
				'page_name'=>$page_name,
				'page_image'=>$page_image_path,
				'description'=>$description,
				'content'=>$imgStr.$this->phpeolToHtml((string)$article->Content),
			];
			
			$this->epaperDb->set_catid($this->catid);
			$id = $this->epaperDb->add_content($ins, true);
			// $r = $epaperDb->get_content($this->catid, $id);
		}
	}

	/**
	 * 换行转为p标签
	 */
	private function phpeolToHtml(string $str) :string {
		$tempInfo = $str;
		$tempInfo = explode(PHP_EOL,$tempInfo);		
		$tempStr = '';
		foreach ($tempInfo as $tempValue){
			$content = mb_ereg_replace("　","",$tempValue);
			$content = trim($content);
			// $content = $tempValue;
			if($content)
				$tempStr .= '<p style="text-indent:2em;margin-top:13px;">'.$content.'</p>';
				// $tempStr .= '<p>&ensp;&ensp;&ensp;&ensp;'.$content.'</p>';
		}
		return $tempStr;
	}

	/**
	 * Image
	 */
	private function contentImage(string $str, string $alt="") :string {
		return '<p style="margin-top:13px;"><img src="'.$str.'" alt="'.$alt.'" style="width:100%;" /></p>'."\n";
	}
	
	/**
	 * 获取微信小程序二维码
	 */
	public function getWxQRcode(){
		return 22;
	}

}